<template>
  <div>
    <search @search="handleSearchByKeyword" @add="handleOpenDialog"/>
    <template>
      <ms-table @rowClick="handleRowClick" :table-props="tableProps" :data-api="dataUrl" ref="dataTable" size="small">
        <el-table-column label="操作" slot="tool">
          <template slot-scope="scope">
            <el-button
              size="mini"
              v-permission="['dictType:save']"
              @click="handleOpenDialog(scope.row.id)">编辑</el-button>
            <el-button
              size="mini"
              @click="handleBeforeDelRow(scope.row.id)"
              v-permission="['dictType:del']"
              type="danger">删除</el-button>
          </template>
        </el-table-column>
      </ms-table>
    </template>
    <info :title="title" ref="infoForm" :dialog-visible="dialog1" :form-id="formId" @dataFresh="handleCanleDialog" @close="handleCanleDialog" />
  </div>
</template>

<script>
import { MsTable } from '@/common/table'
import Search from './Search'
import Info from './Info'
import common from '@/mixins/common'

// api
import { checkChildren } from '@/api/sys/dict'
export default {
  components: {
    MsTable,
    Search,
    Info
  },
  mixins: [common],
  data() {
    return {
      tableProps: [
        { index: 'typeValue', label: '类型名称' },
        { index: 'name', label: '标识' }
      ],
      dataUrl: '/sys/dictType/list',
      delUrl: '/sys/dictType/del',
      mainTitle: '字典父类型'
    }
  },
  methods: {
    handleRowClick(val = '') {
      this.$emit('clickRow', val[0] ? val[0].id : val)
    },
    handleBeforeDelRow(formId) {
      return new Promise((resolve) => {
        // 查询是否存在子节点
        checkChildren(formId).then((res) => {
          let isExistChild = res.obj
          if (isExistChild) {
            this.$confirm('当前字典存在子节点，是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.handleDelRow(formId)
              this.handleRowClick()
            }).catch(() => {
              // do noting
            })
          } else {
            this.handleDelRow(formId)
          }
        })
      })
    }
  }
}
</script>
